#include "linux/pinctrl/pinctrl.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

#define BUFFER_SIZE 256

void write_to_device(int fd, const char *data) {
    lseek(fd, 0, SEEK_SET); // Move to the beginning
    if (write(fd, data, strlen(data)) == -1) {
        perror("write");
    }
}

void read_from_device(int fd, char *buf, size_t size) {
    lseek(fd, 0, SEEK_SET); // Move to the beginning
    ssize_t len = read(fd, buf, size);
    if (len == -1) {
        perror("read");
    } else {
        printf("APP read : ");
        for (ssize_t i = 0; i < len; i++) {
            printf("%02x ", (unsigned char)buf[i]);
        }
        printf("\n");
    }
}

int main(int argc, char **argv) {
    int fd;
    char buf[BUFFER_SIZE];
    
    if (argc != 3) {
        fprintf(stderr, "Usage: %s [write|read] <data>\n", argv[0]);
        return 1;
    }

    fd = open("/dev/myat24c02", O_RDWR);
    if (fd == -1) {
        perror("open");
        return 1;
    }

    if (strcmp(argv[1], "write") == 0) {
        write_to_device(fd, argv[2]);
    } else if (strcmp(argv[1], "read") == 0) {
        read_from_device(fd, buf, sizeof(buf));
    } else {
        fprintf(stderr, "Invalid command. Use 'write' or 'read'.\n");
        close(fd);
        return 1;
    }

    close(fd);
    return 0;
}
